import { baseUrl } from './api.js'
 
function pay(orderSn,total,type){
	return new Promise((resolve, reject) => {
		//验证登录
		uni.showLoading({
			title:"正在支付...",
			mask:true
		})
		//发起请求
		uni.request({
			url: baseUrl+'/d/wxpay/pay',
			method:'POST', 
			header : {
				token: uni.getStorageSync('token')
			}, 
			data: {
				openid: uni.getStorageSync('openid'),
				orderSn: orderSn,
				total: total,
				type: type,
			},
			success:(res)=>{
				if(res.data.code == 1){//调起成功 
					uni.requestPayment({
						provider: 'wxpay',
						timeStamp: res.data.data.pay.timeStamp,
						nonceStr: res.data.data.pay.nonceStr,
						package: res.data.data.pay.package,
						signType: res.data.data.pay.signType,
						paySign: res.data.data.pay.paySign,
						success: function (res) {//支付成功
							uni.showToast({
								title:'支付成功',
								icon:'none' ,
							});
							resolve()
						},
						cancel: function() {
							uni.showToast({
								title:'取消支付',
								icon:'none' ,
							});	
							if(type=='1'){
								setTimeout(function(){
									uni.redirectTo({
										url:"/pages/vote/vote"
									})
								},2000)
							}
							reject()							  	
						},
						fail: function(err) {
							uni.showToast({
								icon:"none",
								title:'支付失败'
							})
							if(type=='1'){
								setTimeout(function(){
									uni.redirectTo({
										url:"/pages/vote/vote"
									})
								},2000)
							}
							reject()							  
						},
					});
				}else if(res.data.code == 401){//登录失效
					uni.navigateTo({
						url:"/pages/login/login",
						success() {
							uni.showToast({
								icon:"none",
								title:"请登录后操作"
							})
						}
					})
					reject()
				}else{
					uni.showToast({
						icon:"none",
						title:res.data.msg
					}) 	
					reject(res.data.msg)						
				}
			},
			fail(err) {
				// 一般是网络错误
				uni.showModal({
					content:'网络错误请重试',
					showCancel:false
				})
				reject(new Error('网络错误请重试'))
			},
			complete() {
				uni.hideLoading()
			}
		})
	}) 
}

module.exports = {
    pay: pay
}
